package com.ruoyi.base.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.base.mapper.BaseTeacherMapper;
import com.ruoyi.base.domain.BaseTeacher;
import com.ruoyi.base.service.IBaseTeacherService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidationUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 老师Service业务层处理
 * 
 * @author yepanpan
 * @date 2020-11-09
 */
@Service
public class BaseTeacherServiceImpl implements IBaseTeacherService {
	private static final Logger log = LoggerFactory.getLogger(BaseTeacherServiceImpl.class);

	@Autowired
	private BaseTeacherMapper baseTeacherMapper;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysConfigService configService;

    @Autowired
    private SysDeptMapper sysDeptMapper;
    
	/**
	 * 查询老师
	 * 
	 * @param id 老师ID
	 * @return 老师
	 */
	@Override
	public BaseTeacher selectBaseTeacherById(Long id) {
		return baseTeacherMapper.selectBaseTeacherById(id);
	}
	/**
     * 查询教师
     * 
     * @param userId 教师用户ID
     * @return 教师
     */
	@Override
    public BaseTeacher findTeacherByUser(Long userId) {
		BaseTeacher cond = new BaseTeacher();
		cond.setUserId(userId);
		return baseTeacherMapper.findTeacher(cond);		
	}

	/**
	 * 查询老师列表
	 * 
	 * @param baseTeacher 老师
	 * @return 老师
	 */
	@Override
	public List<BaseTeacher> selectBaseTeacherList(BaseTeacher baseTeacher) {
		List<BaseTeacher> list = baseTeacherMapper.selectBaseTeacherList(baseTeacher);
		for(BaseTeacher bt:list) {
			if(bt.getIdcard() == null || bt.getIdcard().length() < 18) continue;
			
			bt.setIdcard(bt.getIdcard().substring(0,8)+"******"+bt.getIdcard().substring(14));
		}
		return list;
	}

	/**
	 * 新增老师
	 * 
	 * @param baseTeacher 老师
	 * @return 结果
	 */
	@Override
    @Transactional
	public int insertBaseTeacher(BaseTeacher baseTeacher) {
    	//同步用户信息
		long userId = saveOrUpdateUser(baseTeacher, SecurityUtils.getUsername());
		baseTeacher.setUserId(userId);
		return baseTeacherMapper.insertBaseTeacher(baseTeacher);
	}

	/**
	 * 修改老师
	 * 
	 * @param baseTeacher 老师
	 * @return 结果
	 */
	@Override
    @Transactional
	public int updateBaseTeacher(BaseTeacher baseTeacher) {
    	//同步用户信息
		long userId = saveOrUpdateUser(baseTeacher, SecurityUtils.getUsername());
		baseTeacher.setUserId(userId);
		return baseTeacherMapper.updateBaseTeacher(baseTeacher);
	}

	/**
	 * 批量删除老师
	 * 
	 * @param ids 需要删除的老师ID
	 * @return 结果
	 */
	@Override
	public int deleteBaseTeacherByIds(Long[] ids) {

    	for(Long id:ids) {
    		BaseTeacher bs = baseTeacherMapper.selectBaseTeacherById(id);
			if(bs != null) {
		    	sysUserService.deleteUserById(bs.getUserId());
			}
		}
    	
		return baseTeacherMapper.deleteBaseTeacherByIds(ids);
	}

	/**
	 * 删除老师信息
	 * 
	 * @param id 老师ID
	 * @return 结果
	 */
	@Override
	public int deleteBaseTeacherById(Long id) {

		BaseTeacher bs = baseTeacherMapper.selectBaseTeacherById(id);
    	if(bs == null) return 0;
    	
    	sysUserService.deleteUserById(bs.getUserId());
    	
		return baseTeacherMapper.deleteBaseTeacherById(id);
	}

	@Override
	public int updateBaseTeacherStatus(Long[] ids, String status) {
    	for(Long userId:ids) {
    		SysUser u = new SysUser();
    		u.setUserId(userId);
    		u.setStatus("1".equals(status) ? "0" : "1");
        	sysUserService.updateUserStatus(u);
    	}
		return baseTeacherMapper.updateBaseTeacherStatus(ids, status);
	}

	@Override
    @Transactional
	public String importTeacher(List<BaseTeacher> teacherList, Boolean isUpdateSupport, String operName) {

		if (StringUtils.isNull(teacherList) || teacherList.size() == 0) {
			throw new CustomException("导入数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for (BaseTeacher vo : teacherList) {
			List<String> vs = ValidationUtils.validate(vo);
			if (vs != null) {
				failureNum++;
				failureMsg.append(
						"<br/>" + failureNum + "、教师 " + vo.getName() + " 数据不完整：" + CollectionUtils.join(vs, ","));
				continue;
			}
			try {
				 // 验证部门是否存在
            	SysDept dd = sysDeptMapper.selectDeptByName(vo.getDeptName());
            	if(dd == null) {
            		throw new CustomException("部门不"+vo.getDeptName()+"存在");
            	}
            	vo.setDeptId(dd.getDeptId());
				
				// 查找旧数据
				BaseTeacher cond = new BaseTeacher();
				cond.setCode(vo.getCode());
				BaseTeacher old = baseTeacherMapper.findTeacher(cond);
				if (StringUtils.isNull(old)) {					
					this.insertBaseTeacher(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、教师 " + vo.getName() + " 导入成功");
				} else if (isUpdateSupport) {
					vo.setId(old.getId());
					this.updateBaseTeacher(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、教师 " + vo.getName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、教师 " + vo.getName() + " 已存在");
				}
				
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、教师 " + vo.getName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();

	}
	
	private long saveOrUpdateUser(BaseTeacher baseTeacher, String operName) {    
		SysUser user = null;
		if(baseTeacher.getUserId() != null) {
			user = sysUserService.selectUserById(baseTeacher.getUserId());
			user.setUpdateTime(DateUtils.getNowDate());
			user.setDeptId(baseTeacher.getDeptId());
			user.setEmail(baseTeacher.getEmail());
			user.setNickName(baseTeacher.getName());
			user.setPhonenumber(baseTeacher.getPhone());
			user.setSex(baseTeacher.getSex());
			
			sysUserService.updateUser(user);
			return user.getUserId();
		}
		user = sysUserService.selectUserByUserName(baseTeacher.getCode());
		if(user != null) {
			user.setUpdateTime(DateUtils.getNowDate());
			user.setDeptId(baseTeacher.getDeptId());
			user.setEmail(baseTeacher.getEmail());
			user.setNickName(baseTeacher.getName());
			user.setPhonenumber(baseTeacher.getPhone());
			user.setSex(baseTeacher.getSex());
			
			sysUserService.updateUser(user);
		}else {

	        String password = configService.selectConfigByKey("sys.user.initPassword");
	        String roles[] = configService.selectConfigByKey("base.role.teacher").split(",");
	        Long[] role = new Long[roles.length];
	        for(int i=0;i<roles.length;i++) {
	        	role[i] = Long.parseLong(roles[i]);
	        }
	        String[] posts = configService.selectConfigByKey("base.post.teacher").split(",");
	        Long[] post = new Long[posts.length];
	        for(int i=0;i<posts.length;i++) {
	        	post[i] = Long.parseLong(posts[i]);
	        }
	        
			user = new SysUser();
			user.setCreateBy(operName);
			user.setCreateTime(DateUtils.getNowDate());
			user.setDelFlag("0");
			user.setDeptId(baseTeacher.getDeptId());
			user.setEmail(baseTeacher.getEmail());
			user.setNickName(baseTeacher.getName());
			user.setUserName(baseTeacher.getCode());
			user.setPhonenumber(baseTeacher.getPhone());
			user.setSex(baseTeacher.getSex());
			user.setStatus("0");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setRoleIds(role);
            user.setPostIds(post);
            
            sysUserService.insertUser(user);
		}
		return user.getUserId();
	}
}
